vite-plugin-resolve
Custom resolve module content
English | 简体中文
- Compatible Browser, Node.js and Electron
- You can think of it as an enhanced Vite external plugin
- You can think of it as manually Pre-Bundling
Install
npm i vite-plugin-resolve -D
Usage
import { defineConfig } from 'vite'
import resolve from 'vite-plugin-resolve'
export default defineConfig({
plugins: [
resolve({
vue: `const vue = window.Vue; export { vue as default }`,
}),
]
})
Load a local file
resolve({
'@scope/name': async () => await require('fs').promises.readFile('path', 'utf-8'),
})
Electron
resolve({
electron: `const { ipcRenderer } = require('electron'); export { ipcRenderer };`,
})
Resolve an ES module as an CommonJs module for Node.js
Such as execa, node-fetch
Here, Vite is used as the build tool
You can also choose other tools, such as rollup, webpack, esbuild, swc and so on
import { builtinModules } from 'module'
import { defineConfig, build } from 'vite'
import resolve from 'vite-plugin-resolve'
export default defineConfig({
plugins: [
resolve({
async execa(args) {
await build({
plugins: [
{
name: 'vite-plugin[node:mod-to-mod]',
enforce: 'pre',
resolveId(source) {
if (source.startsWith('node:')) {
return source.replace('node:', '')
}
},
}
],
build: {
outDir: args.dir,
minify: false,
emptyOutDir: false,
lib: {
entry: require.resolve('execa'),
formats: ['cjs'],
fileName: () => `execa.js`,
},
rollupOptions: {
external: [
...builtinModules,
],
},
},
})
},
})
]
})
API
resolve(resolves[, options])
resolves
export interface Resolves {
[moduleId: string]:
| string
| ((args: ResolveArgs) =>
| string
| Promise<string | void>
| void)
| void;
}
export interface ResolveArgs {
dir: string;
}
options
export interface ResolveOptions {
dir: string;
}
How to work
Let's use Vue as an example
resolve({
vue: `const vue = window.Vue; export { vue as default }`,
})
- Create
node_modules/.vite-plugin-resolve/vue.js
and contains the following code
const vue = window.Vue; export { vue as default }
- Create a
vue
alias item and add it to resolve.alias
{
resolve: {
alias: [
{
find: 'vue',
replacement: 'User/work-directory/node_modules/.vite-plugin-resolve/vue.js',
},
],
},
}
- Add
vue
to the optimizeDeps.exclude
by default.
You can avoid it through optimizeDeps.include
export default {
optimizeDeps: {
exclude: ['vue'],
},
}